package net.begincode.common.template;

import com.google.common.base.Stopwatch;
import net.begincode.common.exception.Status;
import net.begincode.common.exception.StatusException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.TimeUnit;

/**
 * 业务模板方法
 */

public abstract class BizTemplate<T> {
    Logger LOGGER = LoggerFactory.getLogger(BizTemplate.class);

    //监控打点名称
    private String monitorMetrix;

    public BizTemplate(String monitorMetrix) {
        this.monitorMetrix = monitorMetrix;
    }

    //参数检查
    public void checkParam() {
    }

    //执行方法
    public abstract T process();

    //执行后处理逻辑,如释放资源
    public void afterProcess() {
    }

    public final T excute() {
        try {
            checkParam();
            Stopwatch stopwatch = Stopwatch.createStarted();
            T t = process();
            LOGGER.info("monitorMetrix={},cost time ={} ",
                    monitorMetrix, stopwatch.elapsed(TimeUnit.MILLISECONDS));
            return t;
        } catch (StatusException e) {
            LOGGER.error(e.getStatusCode().getReason(), e);
            throw e;
        } catch (Exception e) {
            LOGGER.error("内部错误", e);
            throw new StatusException(Status.error(e.getMessage()));
        } finally {
            afterProcess();
        }

    }

    public String getMonitorMetrix() {
        return monitorMetrix;
    }

    public void setMonitorMetrix(String monitorMetrix) {
        this.monitorMetrix = monitorMetrix;
    }
}
